<template>
  <div class="createuser">
    <a-form
      :model="formState"
      v-bind="layout"
      :rules="rules"
      @finish="onFinish"
    >
      <a-form-item name="account" label="账号">
        <a-input v-model:value="formState.account" />
      </a-form-item>
      <a-form-item name="username" label="用户名">
        <a-input v-model:value="formState.username" />
      </a-form-item>
      <a-form-item
        name="password"
        label="密码"
        v-if="formType === FormType.Create"
      >
        <a-input-password v-model:value="formState.password" />
      </a-form-item>
      <a-form-item name="email" label="邮箱">
        <a-input v-model:value="formState.email" />
      </a-form-item>
      <a-form-item name="title" label="职称">
        <a-input v-model:value="formState.title" />
      </a-form-item>
      <a-form-item name="className" label="班级">
        <a-input v-model:value="formState.className" />
      </a-form-item>
      <a-form-item name="profession" label="专业">
        <a-input v-model:value="formState.profession" />
      </a-form-item>
      <a-form-item label="性别" name="gender">
        <a-radio-group v-model:value="formState.gender">
          <a-radio :value="0">男</a-radio>
          <a-radio :value="1">女</a-radio>
        </a-radio-group>
      </a-form-item>
      <a-form-item name="avatarUrl" label="头像">
        <a-upload
          v-model:fileList="fileList"
          action="http://karrysmile.top:8100/api/user/uploadPhoto"
          name="imgFile"
          list-type="picture-card"
          :before-upload="beforeUpload"
          @change="uploadChange"
        >
          <div v-if="fileList.length < 1">
            <plus-outlined />
            <div style="margin-top: 8px">Upload</div>
          </div>
        </a-upload>
      </a-form-item>
      <a-form-item label="身份" name="role">
        <a-radio-group v-model:value="formState.role">
          <a-radio :value="0">管理员</a-radio>
          <a-radio :value="1">实验员</a-radio>
          <a-radio :value="2">教师</a-radio>
          <a-radio :value="3">学生</a-radio>
        </a-radio-group>
      </a-form-item>
      <a-form-item :wrapper-col="{ ...layout.wrapperCol, offset: 8 }">
        <div class="submitbtn">
          <a-button type="primary" html-type="submit">提交信息</a-button>
        </div>
      </a-form-item>
    </a-form>
  </div>
  <a-modal>
    <a-form-item> </a-form-item>
  </a-modal>
</template>

<script lang="ts" setup>
import { ref, watch } from "vue";
import {
  getUserInfoById,
  userCreate,
  updateUserInfo,
} from "@/api/methods/userReq";
import { Rule } from "ant-design-vue/es/form/interface";
import { Message } from "@/utils/message";
import { useRouteQuery } from "@vueuse/router";
import { FormType } from "@/EnvEnum/form";
import { useRouter } from "vue-router";
import { UploadProps } from "ant-design-vue";
import { getUrlQuery } from "@/utils/common";
import { userInfo } from "@/utils/userInfo";
import { userInfoJson } from "@/utils/userInfo";

const router = useRouter();
const userId = useRouteQuery<string, number>("userId", undefined, {
  transform: Number,
});
const formType = useRouteQuery<string, number>("formType", undefined, {
  transform: Number,
});
watch(
  () => userId.value,
  async () => {
    if (formType.value === FormType.Update) {
      const userData = await getUserInfoById({ id: userId.value });
      formState.value = userData.data;
      if (formState.value.avatarUrl) {
        const name = formState.value.avatarUrl.split("/");
        fileList.value.push({
          uid: "-1",
          name: name[name.length - 1],
          status: "done",
          url: formState.value.avatarUrl,
        });
      }
    }
  },
  { immediate: true }
);
const layout = {
  labelCol: { span: 8 },
  wrapperCol: { span: 8 },
};
const rules: Record<string, Rule[]> = {
  account: [{ required: true, message: "请填写账号！", trigger: "change" }],
  username: [
    {
      required: true,
      message: "请填写用户名！",
      trigger: "change",
    },
  ],
  password: [
    {
      required: true,
      message: "请填写密码！",
      trigger: "change",
    },
  ],
  email: [{ type: "email", required: true, message: "请输入格式正确的邮箱" }],
};
const formState = ref({
  account: "",
  avatarUrl: "",
  className: "",
  gender: 0,
  id: "",
  password: "",
  profession: "",
  role: 0,
  title: "",
  email: "",
  username: "",
});
formState.value.id = getUrlQuery().userId || "";
const fileList = ref<any>([]);
const beforeUpload = (file: UploadProps["fileList"][number]) => {
  const isJpgOrPng = file.type === "image/jpeg" || file.type === "image/png";
  if (!isJpgOrPng) {
    Message("warning", "图片格式：png/jpeg");
  }
  const isLt2M = file.size / 1024 / 1024 < 2;
  if (!isLt2M) {
    Message("warning", "图片过大：只能2M以内");
  }
  return isJpgOrPng && isLt2M;
};
const uploadChange = (data: any) => {
  if (data.file?.status === "done") {
    formState.value.avatarUrl = data.file.response.data;
  }
};
const onFinish = async (values: any) => {
  if (formType.value === FormType.Create) {
    const res = await userCreate({ ...values, id: formState.value.id });
    if (res.code === 20000) {
      Message("success", "添加用户成功", () => {
        //TODO 清空用户表单
        formState.value = {
          account: "",
          avatarUrl: "",
          className: "",
          gender: 0,
          id: "",
          password: "",
          profession: "",
          role: 0,
          title: "",
          email: "",
          username: "",
        };
        router.push({ name: "userList" });
      });
    }
  } else {
    const res = await updateUserInfo({ ...values, id: formState.value.id });
    if (res.code === 20000) {
      Message("success", "用户信息修改成功", () => {
        if (userInfo.value.id === formState.value.id) {
          //如果修改的是自己的用户信息直接退出登录
          // 清空localStorage内容
          userInfoJson.value = "";
          router.push({ path: "/home" });
        }
        router.go(-1);
      });
    }
  }
};
</script>
<style scoped lang="scss">
/* @import url(); 引入css类 */
.submitbtn {
  display: flex;
  justify-content: space-around;
}
</style>
